package top.ewind.controller.admin.device;

import java.io.File;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;

import top.ewind.controller.common.AdminRootCtrl;
import top.ewind.jfinal.ext.kit.excel.PoiImporter;
import top.ewind.jfinal.ext.kit.excel.Rule;
import top.ewind.jfinal.ext.render.excel.PoiRender;
import top.ewind.util.DateUtil;
import top.ewind.util.SecurityUtil;

public class DeviceCtrl extends AdminRootCtrl {

	public void index() {
		int nid = getSessionAttr("nid");
		setAttr("plist",Db.find("select * from device_product where nid = ? order by intime desc",nid));
		render("index.html");
	}

	public void profile() {
		int nid = getSessionAttr("nid");
		String filter = " t.nid ="+nid+SecurityUtil.sqlFilter(getPara("param", ""));
		renderJson(Db.paginate(getParaToInt("page", 1), getParaToInt("rp", 10), "select t.*,p.pname ", " from device t left join device_product p on p.id = t.pid where " + filter));
	}
	
	public void edit() {
		int nid = getSessionAttr("nid");
		Record device = Db.findById("device",getPara(0));
			if (device != null && device.getInt("nid")==nid) {
				setAttr("item", device);
				setAttr("product", Db.findById("device_product",device.getStr("pid")));
		} else {
			setAttr("plist",Db.find("select * from device_product where nid = ? order by intime desc", nid));
		}
		render("edit.html");
	}
	public void macajax(){
		String mac = getPara("mac");
		Record device = Db.findById("device",mac);
		if(device!=null){
			renderJson("res",0);
		}else{
			renderJson("res",1);
		}
		
	}
	@Before(Tx.class)
	public void delete() {
		boolean ret = false;
		if(StrKit.notBlank(getPara("id"))){
			ret = Db.deleteById("device",getPara("id"));
			Db.update("delete from device_bind where deviceid = ?",getPara("id"));
		}
		if(StrKit.notBlank(getPara("ids"))){
			ret = Db.update("delete from device where id in ("+getPara("ids")+")")>0;
			Db.update("delete from device_bind where deviceid in ("+getPara("ids")+")");
		}
		if (ret)
			renderJson("msg", "success");
		else
			renderJson("msg", "删除失败，请重试！");
	}

	public void save() {
		int nid = getSessionAttr("nid");
		boolean ret = false;
		Record device = Db.findById("device",getPara("device.id"));
		if (device!=null) {
			injectParas(device,"sn","remark");
			ret = Db.update("device", device);
		} else {
			Record product = Db.findById("device_product",getPara("pid"));
			if(product!=null){
				device = new Record().set("id",getPara("device.id").toLowerCase()).set("nid", nid).set("intime", new Date());
				injectParas(device,"sn","pid","remark");
				if(StrKit.notBlank(product.getStr("pno"))){
					//TODO 微信注册
				}
				else{
					device.set("qrticket", SecurityUtil.md5(getPara("id").toLowerCase()+product.getStr("pmkey"))+getPara("id").toLowerCase());
				}
				ret = Db.save("device", device);
			}
		}
		if (ret)
			renderJson("msg", "success");
		else
			renderJson("msg", "保存失败，请重试！");
	}
	
	public void excelimport() {
		int nid = getSessionAttr("nid");
		boolean ret = true;
		String folder = Integer.toString(nid);
		UploadFile excelFile = getFiles(folder).get(0);
		String filePath = PathKit.getWebRootPath() + File.separator + "upload" + File.separator + folder + File.separator + excelFile.getFileName();
		Rule rule = new Rule();
		rule.setStart(1);
		List<List<String>> records = PoiImporter.readSheet(new File(filePath), rule);
		Record product = Db.findById("device_product",getPara("pid"));
		int rcount = 0;
		if(product==null){
			ret = false;
		}
		else{
			for (List<String> ls : records) {
				if (ls.size() >= 3) {
					Record de = Db.findById("device", ls.get(0).toLowerCase());
					if(de==null){
					Record device = new Record().set("nid",nid).set("id", ls.get(0).toLowerCase()).set("sn", ls.get(1)).set("remark", ls.get(2))
							/*.set("field1", ls.get(3)).set("field2", ls.get(4))*/
							.set("pid", product.getStr("id")).set("intime", new Date())
							.set("qrticket", SecurityUtil.md5(ls.get(0).toLowerCase()+product.getStr("pmkey"))+ls.get(0).toLowerCase());
					if(Db.save("device",device)){
						Record dm = new Record().set("nid", nid).set("mid", getSessionAttr("mid")).set("mac", device.getStr("id")).set("stat", 0).set("intime", new Date()).set("remark", "新增一台设备");
						Db.save("device_message", dm);
						rcount ++;
					}
				}
				}
			}
		}
		if (ret) {
			renderHtml("成功导入了" + rcount + "条数据。");
		}else {
			renderHtml("导入出错！请重试。");
		}
	}
	
	public void exportexcel() {
		int nid = getSessionAttr("nid");
		List<Record> dlist = Db.find("select * from device where nid = " + nid + SecurityUtil.sqlFilter(getPara("param")));
		String[] headers = new String[] { "MAC地址", "SN码", "二维码ticket", "创建时间", "备注" };
		String[] columns = new String[] { "id",  "sn", "qrticket","intime", "remark" };
		render(PoiRender.me(dlist).fileName("设备列表" + DateUtil.now() + ".xls").headers(headers).columns(columns));
	}
	
	public void bind(){
		Record device = Db.findById("device",getPara(0));
		if(device!=null){
			setAttr("device", device);
			render("bind.html");
		}
		else renderNull();
	}
	

	public void bindprofile() {
		int nid = getSessionAttr("nid");
		String filter = " t.nid ="+nid+SecurityUtil.sqlFilter(getPara("param"));
		renderJson(Db.paginate(getParaToInt("page", 1), getParaToInt("rp", 10), "select t.*,u.username", " from device_bind t inner join device_user u on t.userid = u.id where " + filter));
	}
	
	public void updatebtype() {
		int nid = getSessionAttr("nid");
		if (StrKit.notBlank(getPara("id")) && StrKit.notBlank(getPara("btype"))) {
			Record item = Db.findById("device_bind",getPara("id"));
			if (item != null && item.getInt("nid").intValue() == nid) {
				item.set("btype", getPara("btype"));
				Db.update("device_bind",item);
				renderJson("msg", "success");
				return;
			}
		}
		renderJson("msg", "设置失败，请重试！");
	}
	
	public void binddelete() {
		boolean ret = false;
		if(StrKit.notBlank(getPara("id"))){
			ret = Db.deleteById("device_bind",getPara("id"));
		}
		if(StrKit.notBlank(getPara("ids"))){
			ret = Db.update("delete from device_bind where id in ("+getPara("ids")+")")>0;
		}
		if (ret)
			renderJson("msg", "success");
		else
			renderJson("msg", "删除失败，请重试！");
	}
	
	public void stat() {
		int nid = getSessionAttr("nid");
		if (StrKit.notBlank(getPara(0))) {
			Record device = Db.findById("device",getPara(0));
			if (device != null && device.getInt("nid")==nid) {
				setAttr("device", device);
				setAttr("product", Db.findById("device_product",device.getStr("pid")));
			}
		} else {
			setAttr("plist",Db.find("select * from device_product where nid = ? order by intime desc", nid));
		}
		render("stat.html");
	}
}